import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { Form, Input, Toast } from "antd-mobile";
import { BottomBtn } from "@components";
import { REQUIRED_RULE, BARCODE_PARSER } from "@common/constants";
import { createAction, callNativeApi } from "@common/utils";
import {
  POP_PAGE_STACK,
  PUSH_PAGE_STACK,
  SET_SCAN_DATA,
} from "@store/global-state/action-types";
import {
  SAGA_TMP_PALLET_STASH_OPS_DATA,
  SAGA_TMP_PALLET_FINISH_OPS,
  SAGA_TMP_PALLET_LOAD_OPS_FORM,
} from "@store/tmp-pallet/saga-types";
import { CLEAR_TMP_PALLET_OPS_FORM } from "@store/tmp-pallet/action-types";

const TmpPalletOps = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const [form] = Form.useForm();
  const opsFormData = useSelector((state) => state.tmpPallet.opsFormData);
  const palletDataId = useSelector((state) => state.tmpPallet.palletDataId);
  const scandata = useSelector((state) => state.globalState.scandata);

  useEffect(() => {
    let id = searchParams.get("id");
    dispatch(createAction(SAGA_TMP_PALLET_LOAD_OPS_FORM, { id }));
    return () => {
      dispatch(createAction(SET_SCAN_DATA, null));
      dispatch(createAction(CLEAR_TMP_PALLET_OPS_FORM));
    };
  }, []);

  useEffect(() => {
    if (opsFormData) {
      form.setFields([
        { name: "warehouseName", value: opsFormData.warehouseName },
        { name: "palletBarcode", value: opsFormData.palletBarcode },
      ]);
    }
  }, [opsFormData]);

  const setItemFields = ({ barcode, parseResult }) => {
    let { itemCode, itemName } = parseResult;
    form.setFields([
      { name: "itemBarcode", value: barcode },
      { name: "itemCode", value: itemCode },
      { name: "itemName", value: itemName },
      { name: "batchNum", value: parseResult.batchNum },
      { name: "qty", value: parseResult.qty },
    ]);
  };

  useEffect(() => {
    if (scandata) {
      callNativeApi({
        classFullName: BARCODE_PARSER,
        action: "parse",
        params: { barcode: scandata, bizType: "TMP_PALLET" },
        needNonce: false,
      })
        .then((resp) => {
          let result = resp.data ? resp.data.payload : resp.payload;
          if (result.ruleType === "ITEM") {
            // 物料码
            setItemFields({
              barcode: scandata,
              parseResult: result,
            });
          }
          dispatch(createAction(SET_SCAN_DATA, null));
          return;
        })
        .catch((error) => console.log(error));
    }
  }, [scandata]);

  const handleContinue = () => {
    form
      .validateFields()
      .then(() => {
        let { itemBarcode, qty } = form.getFieldValue();
        dispatch(
          createAction(SAGA_TMP_PALLET_STASH_OPS_DATA, {
            tmpPalletDataId: searchParams.get("id"),
            itemBarcode,
            qty,
            callback: () => {
              Toast.show({
                icon: "success",
                content: "保存成功",
                maskClickable: false,
              });
              form.setFields([
                { name: "itemBarcode", value: "" },
                { name: "itemCode", value: "" },
                { name: "itemName", value: "" },
                { name: "batchNum", value: "" },
                { name: "qty", value: "" },
              ]);
            },
          })
        );
        return;
      })
      .catch((error) => console.log(error));
  };

  const openDetails = () => {
    let path = `/app/tmp-pallet/details?id=${searchParams.get("id")}`;
    navigate(path);
    dispatch(createAction(PUSH_PAGE_STACK, path));
  };

  const handleFinish = () => {
    dispatch(
      createAction(SAGA_TMP_PALLET_FINISH_OPS, {
        tmpPalletDataId: palletDataId,
        callback: () => {
          dispatch(createAction(POP_PAGE_STACK, navigate));
        },
      })
    );
  };

  return (
    <>
      <div style={{ marginTop: "45px", marginBottom: "65px" }}>
        <Form form={form} mode="card">
          <Form.Header>基本信息</Form.Header>
          <Form.Item name="warehouseName" label="仓库">
            <Input readOnly />
          </Form.Item>
          <Form.Item name="palletBarcode" label="托码">
            <Input readOnly />
          </Form.Item>
          <Form.Header />

          <Form.Header>
            <span>物料信息</span>
            <span style={{ float: "right" }}>
              累计提交数据: {opsFormData?.recordNum ? opsFormData.recordNum : 0}
              条
            </span>
          </Form.Header>
          <Form.Item name="itemBarcode" label="物料条码" rules={REQUIRED_RULE}>
            <Input placeholder="扫码获取" readOnly />
          </Form.Item>
          <Form.Item name="itemCode" label="物料编码">
            <Input readOnly />
          </Form.Item>
          <Form.Item name="itemName" label="物料名称">
            <Input readOnly />
          </Form.Item>
          <Form.Item name="batchNum" label="批次号">
            <Input readOnly />
          </Form.Item>
          <Form.Item name="qty" label="数量" rules={REQUIRED_RULE}>
            <Input placeholder="请扫码或输入" />
          </Form.Item>
          <Form.Header />
        </Form>
      </div>
      <BottomBtn
        items={[
          { btnTxt: "继续", color: "danger", handler: handleContinue },
          {
            btnTxt: "明细",
            disabled: !(opsFormData?.recordNum > 0),
            handler: openDetails,
          },
          {
            btnTxt: "完成",
            color: "primary",
            disabled: !(opsFormData?.recordNum > 0),
            handler: handleFinish,
          },
        ]}
      />
    </>
  );
};

export default TmpPalletOps;
